package com.hgy.crowd.handler;


import java.util.concurrent.TimeUnit;
import com.hgy.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author He
 * @Date 2020/6/30 16:47
 */
@RestController
public class RedisHandler {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/set/key/value/remote")
    ResultEntity<String> setStringKeyAndValueRemote(@RequestParam("key") String key,
                                                    @RequestParam("value") String value){
        try{
            ValueOperations<String, String> stringStringSetOperations = stringRedisTemplate.opsForValue();
            stringStringSetOperations.set(key,value);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }


    @RequestMapping("/set/key/value/timeout/remote")
    ResultEntity<String> setStringKeyAndValueWithTimeoutRemote(@RequestParam("key")String key,
                                                               @RequestParam("value")String value,
                                                               @RequestParam("time")Long time,
                                                               @RequestParam("timeUnit") TimeUnit timeUnit) {
        try{
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            stringStringValueOperations.set(key,value,time,timeUnit);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/get/string/value/by/key")
    ResultEntity<String> getStringValueByKeyRemote(@RequestParam("key") String key){
        try {
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            String s = stringStringValueOperations.get(key);
            return ResultEntity.successWithData(s);
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }


    @RequestMapping("/remove/string/key")
    ResultEntity<String> removeRedisKeyRemote(@RequestParam("key") String key){
        try {
            stringRedisTemplate.delete(key);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }
}
